package com.aliengen.thingple.driverapp.data.models;

import com.aliengen.thingple.driverapp.data.exception.InvalidTagException;
import com.aliengen.thingple.driverapp.data.local.BundleModel;

import java.util.HashMap;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class BundleTag extends Tag {
    protected static HashMap<byte[], BundleTag> bundles = new HashMap<>();
    protected BundleModel bundle;

    protected int bundle_id;
    protected String bundle_reference;

    public static BundleTag get(byte[] tag) throws InvalidTagException
    {
        if(bundles.containsKey(tag))
        {
            return bundles.get(tag);
        }

        BundleTag o = new BundleTag(tag);
        bundles.put(tag, o);

        return o;
    }

    public BundleTag(byte[] tag) throws InvalidTagException
    {
        super(tag);

        if(this.tagType != 0x04)
        {
            throw new InvalidTagException("Not bundle tag!");
        }
        this.bundle_id = ((b(12) & 0xFF) << 24) + ((b(13) & 0xFF) << 16) + ((b(14) & 0xFF) << 8) + (b(15) & 0xFF);

        if(this.bundle_id == 0)
        {
            this.bundle_id = ((b(10) & 0xFF) << 8) + (b(11) & 0xFF);
        }

        this.bundle_reference = String.format("%05d", this.bundle_id);
    }

    @Override
    public String toString() {
        return "Bundle " + this.bundle_reference;
    }
}
